<template>
    <div class="outer">
        <div class="title-d">
            <div class="title-d-left">
                {{ dayTimeO }}
            </div>
            <div class="title-d-middle">
                <span>{{ title }}</span>
                <span class="phone">{{ phone }}</span>
            </div>
            <div class="title-d-right"> 累计运行时间：{{ dayTimeT }}</div>
        </div>
        <div class="body-d">
            <div class="yichuan-body-left">
                <!--服务详情数据-->
                <ServiceDetails
                    theme="dark"
                    :refreshState="refreshState"
                    :setting="setting"
                    class="service-details"
                    @handleClick="handlePhoneDialog"
                />
                <!--一线医疗点每日工作动态-->
                <DailyWorkTrends theme="dark" :refreshState="refreshState" class="daily-work-trends" />
            </div>
            <div class="body-d-middle">
                <china-map
                    :showFooter="false"
                    :computedCenter="false"
                    :mapOptions="YinChuanOptionTest"
                    :showHospitalList="showHospitalList"
                    :hospitalList="hospitalList"
                    @clearHospitalList="clearHospitalList"
                />
            </div>
            <div class="body-d-right">
                <!--健康终端报警-->
                <TerminalAlarm :refreshState="refreshState" :setting="setting" @emit-view-detail="handleEmployeeDialog" />
                <!--员工队伍健康状况-->
                <EmployeeHealth theme="dark" :refreshState="refreshState" :setting="setting" />
                <!--体检数据-->
                <PhysicalExaminationData :key="tabState" :refreshState="refreshState" :setting="setting" />
            </div>
        </div>
        <div class="bottom-d"></div>
    </div>
</template>
<script lang="ts" setup>
    import { onUnmounted, ref, nextTick, onMounted } from 'vue';
    import ServiceDetails from '/@/views/yinChuanTest/componetns/ServiceDetails.vue';
    import DailyWorkTrends from '/@/views/yinChuanTest/componetns/dailyWorkTrends.vue';
    import PhysicalExaminationData from '/@/views/yinChuanTest/componetns/physicalExaminationData.vue';
    import TerminalAlarm from '/@/views/yinChuanTest/componetns/TerminalAlarm.vue';
    import EmployeeHealth from '/@/views/yinChuanTest/componetns/employeeHealth.vue';
    import ChinaMap from '/@/views/yinChuanTest/componetns/chinaMap.vue';
    import { useTopTime } from '/@/utils/utils.ts';
    import { useRefresh } from '/@/hooks/autoRefresh';
    import { DEFAULT_TIME } from '/@/hooks/autoRefresh/pageRefreshTime.ts';
    import { useRoute } from 'vue-router';
    import { DataType, getSettings, ThemeType } from '/@/utils/settings.ts';
    import { ServerDetailType } from '/@/components/body-d-left/bodyLeftHooks.ts';
    import { useUserStore } from '/@/store/modules/user.ts';
    import { Map } from '/@/assets/mapUtils/map.ts';

    const YinChuanOptionTest = {
        center: [108.32, 36.45], //地图中心点
        zoom: 7, //地图显示的缩放级别
        mapStyle: 'darkblue', //地图样式
    };
    const title = ref('应急就医服务中心');
    const phone = '(xxxx-xxxxxxx)';
    const route = useRoute();
    const setting = getSettings(DataType.yinChuan);
    onMounted(() => {
        init();
        document.title = title.value;
        document.addEventListener('visibilitychange', checkTabState);
        //设置主题
        store.setThemeType(ThemeType.dark);
    });
    const store = useUserStore();

    onUnmounted(() => {
        clearInterval(interval.value);
        document.removeEventListener('visibilitychange', checkTabState);
    });
    const tabState = ref('');

    //判断窗口是否处于激活状态，切换浏览器tab会导致部分echarts显示不正常
    function checkTabState() {
        tabState.value = document.hidden ? 'inactive' : 'active';
    }

    const { refreshState } = useRefresh(DEFAULT_TIME);
    const dayTimeO = ref();
    const dayTimeT = ref();
    const interval = ref(1);

    function init() {
        getTime();
        interval.value = setInterval(() => {
            getTime();
        }, 1000);
    }

    function getTime() {
        const { timeLeft, timeRight } = useTopTime();
        dayTimeO.value = timeLeft;
        dayTimeT.value = timeRight;
    }

    const phoneDialogTitle = ref('呼入电话');
    const phoneDialogRef = ref();
    //0:处置 1:处理 2:呼入 3:全部
    const phoneType = ref('');

    //呼入电话、受理电话弹窗
    function handlePhoneDialog(item) {
        const { name, key } = item;
        //呼入电话
        if (key == 'gross') {
            phoneType.value = ServerDetailType['gross'];
            //受理电话
            if (key == 'alerdyreceive') {
                phoneType.value = ServerDetailType['alerdyreceive'];
            }
            nextTick(() => {
                phoneDialogTitle.value = name;
                phoneDialogRef.value.openDialog();
            });
        }
    }

    const terminalAlarmDialogRef = ref();

    //终端预警列表弹窗
    function handleEmployeeDialog() {
        terminalAlarmDialogRef.value.openDialog();
    }

    //确认应急求助
    const hospitalList = ref([]); //医院列表
    const showHospitalList = ref(false);

    async function confirmHelp(data) {
        if (!data.lon) return;
        hospitalList.value = [];
        //用户的坐标信息
        let point = [data.lon, data.lat];
        if (data.hospitalList && data.hospitalList.length > 0) {
            try {
                hospitalList.value = await getHospitalList(data.hospitalList, point);
                showHospitalList.value = true;
            } catch (error) {
                console.log('获取医院列表时出错:', error);
            }
        } else {
            console.log('没有医院list');
        }
        Map.getAddressByPoint(point).then((res) => {
            const option = {
                lon: data.lon,
                lat: data.lat,
                position: point,
                name: data.realName,
                address: res,
                sex: data.sex,
            };
            Map.createEmergencyMarker(option);
        });
    }

    async function getHospitalList(hospitalList, userLocation) {
        const hospitalPromises = hospitalList.map(async (item) => {
            item.distance = getDistance(userLocation, [item.lon, item.lat]);
            const { time, routeList } = await getDriveTime(userLocation, [item.lon, item.lat]);
            item.driveTime = time;
            item.routeList = routeList;
            item.userLocation = userLocation;
            return item; // 返回更新后的医院条目
        });
        return Promise.all(hospitalPromises);
    }

    function getDistance(userLocation, destination) {
        const value = Map.getDistance(userLocation, destination);
        return value > 1000 ? (value / 1000).toFixed(2) + 'km' : value + 'm';
    }

    async function getDriveTime(userLocation, destination) {
        let { time, steps } = await Map.getDriveTime(userLocation, destination);
        let h,
            m,
            s = 0;
        if (time <= 60) {
            return {
                time: `${s}秒`,
                routeList: steps,
            };
        }
        if (time > 60 && time < 3600) {
            m = Math.floor(time / 60);
            return {
                time: `${m}分`,
                routeList: steps,
            };
        }
        if (time >= 3600) {
            h = Math.floor(time / 3600);
            m = Math.floor((time - h * 3600) / 60);
            return {
                time: `${h}小时${m}分`,
                routeList: steps,
            };
        }
    }

    function clearHospitalList() {
        hospitalList.value = [];
        showHospitalList.value = false;
    }
</script>
<style lang="less" scoped>
    .outer {
        height: 100%;
        box-sizing: border-box;
        background: url('/@/assets/images/bg.png') no-repeat;
        background-size: 100% 100%;
    }

    .title-d {
        height: 80px;
        line-height: 80px;
        display: flex;
        padding-bottom: 9px;
        background: url('/@/assets/images/top-title.png') no-repeat;
        background-size: 100% 100%;

        .title-d-left,
        .title-d-middle,
        .title-d-right {
            font-size: 27px;
            color: #ffffff;
            line-height: 60px;
            text-align: center;
        }

        .title-d-middle {
            .phone {
                font-size: 27px;
                margin-left: 4px;
            }
        }

        > :nth-child(1) {
            width: 29%;
        }

        > :nth-child(2) {
            width: 42%;
            font-size: 40px;
            font-weight: bold;
        }

        > :nth-child(3) {
            width: 29%;
        }
    }

    .body-d {
        display: flex;
        height: calc(100% - 120px);
        padding-top: 10px;

        > :nth-child(1) {
            width: 24%;
        }

        > :nth-child(2) {
            width: 52%;
        }

        > :nth-child(3) {
            width: 24%;
        }

        //.yichuan-body-left,
        //.body-d-right {
        //    text-align: center;
        //}

        .yichuan-body-left {
            .service-details {
                height: 33%;
            }

            .daily-work-trends {
                height: 67%;
            }
        }

        .body-d-right {
            > :nth-child(n) {
                width: 100%;
                height: calc(100% / 3);
                padding: 10px;
            }
        }

        .body-d-middle {
            display: flex;
            flex-direction: column;
        }
    }

    .bottom-d {
        height: 40px;
        background: url('/@/assets/images/bottom-b.png') no-repeat;
        background-size: 100% 100%;
    }
</style>
